package com.etc.util;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SimpleCORSFilter implements Filter {

//	Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) res;
		HttpServletRequest request = (HttpServletRequest) req;
		if (request.getHeader("Origin") != null)
			response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
		else
			response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Request-Headers", "*");
		response.setHeader("Access-Control-Allow-Credentials", "true");
		response.setHeader("Access-Control-Allow-Methods", "POST,GET,TRACE,OPTIONS,DELETE,PUT,HEAD");
		response.setHeader("Access-Control-Allow-Headers",
				"Content-Type,Origin,Accept,Authorization,X-Requested-With,No-Cache,If-Modified-Since,Pragma,Last-Modified,Cache-Control,Expires,X-E4M-With,token");
		response.setHeader("Access-Control-Max-Age", "3600");
		if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
			response.setHeader("Content-Type", "application/json;charset=utf-8");
			// 这里需要按实际加入代码返回空或者http状态200
			return;
		}
		chain.doFilter(req, res);
	}

	@Override
	public void destroy() {

	}
}
